import axios from "axios"
import Qs from 'qs'
import store from '@/store'
import router from '@/router'

axios.defaults.baseURL = "/api"
axios.defaults.timeout = 5000
if(process.env.NODE_ENV=="production"){
  axios.defaults.baseURL = "/guanpaiadmins/api"
}


// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  //接口错误状态处理，也就是说无响应时的处理
  error => {
    if(error.response.status==401){
      store.commit("setUserInfo",{})
      router.push('/login')
      return null
    }
    return Promise.reject(error.response.status) // 返回接口返回的错误信息
  })

function post(url, data) {

  return new Promise((resp, rej) => {

      let userinfo = store.state.userinfo
      if(  userinfo.token ) {
        data.token = userinfo.token || '__token__'
      }
      axios.post(url, Qs.stringify(data))
        .then(res => {
          
          resp(res.data)
        })
        .catch(err => {
        
          rej(err)
        })
      
    })
    
}

export default post
